<template>
  <view class="container">
    <view class="item">
      <view class="title"><text style="color: red">*</text>标题：</view>
      <uni-easyinput placeholder="请输入标题" v-model="title"></uni-easyinput>
    </view>
    <view class="item">
      <view class="title"><text style="color: red">*</text>分类：</view>
      <uni-data-select
        placeholder="请选择分类"
        @change="handleCategoryChange"
        v-model="categoryID"
        :localdata="categorySelect"
      ></uni-data-select>
    </view>
    <view class="item">
      <view class="title"><text style="color: red">*</text>内容：</view>
      <uni-easyinput type="textarea" placeholder="请输入内容" v-model="content"></uni-easyinput>
    </view>
    <view class="item">
      <view class="title">上传图片（选填，限制4张）</view>
      <uni-file-picker
        ref="upload"
        v-model="showImageVal"
        fileMediatype="image"
        mode="grid"
        fileExtname="jpg,png"
        :limit="4"
        :autoUpload="false"
        @select="handleSelectImage"
      />
    </view>
    <button type="primary" @click="handleSubmit">发布</button>
  </view>
</template>

<script setup>
  import { ref } from 'vue'
  import { GetCircleCategoryList, CreateCircle } from '@/apis/circle'
  import { onLoad } from '@dcloudio/uni-app'

  const title = ref('')
  const content = ref('')
  const categoryID = ref()
  const imageVal = ref([])
  const showImageVal = ref([])
  const uploadedURL = ref([])
  const categorySelect = ref([])

  onLoad(() => {
    GetCircleCategoryList().then((res) => {
      res.data.forEach((item) => {
        categorySelect.value.push({
          value: item.categoryID,
          text: item.category
        })
      })
      // console.log(categoryList.value)
    })
  })

  function handleSelectImage(e) {
    if (e.tempFiles[0].size > 10 * 1024 * 1024) {
      uni.showToast({
        title: '图片不能大于10M',
        position: 'bottom'
      })
      return
    }
    const temp = e.tempFiles[e.tempFiles.length - 1]
    // console.log(temp)
    showImageVal.value = showImageVal.value.concat(temp)
    imageVal.value = imageVal.value.concat(e.tempFilePaths)
    console.log(imageVal.value)
  }
  // 下拉框改变
  function handleCategoryChange(e) {
    categoryID.value = e
  }
  // 提交
  async function handleSubmit() {
    if (title.value === '') {
      uni.showToast({
        icon: 'error',
        title: '标题不能为空'
      })
      return
    }
    if (categoryID.value === undefined) {
      uni.showToast({
        icon: 'error',
        title: '请选择分类'
      })
      return
    }
    if (content.value === '') {
      uni.showToast({
        icon: 'error',
        title: '内容不能为空'
      })
      return
    }
    console.log(imageVal.value)
    if (imageVal.value && imageVal.value.length > 0) {
      // 图片上传
      await new Promise((resolve, reject) => {
        imageVal.value.forEach((item) => {
          // console.log(item);
          uni.uploadFile({
            url: 'https://image.dcwedu.top/api/index.php',
            filePath: item,
            name: 'image',
            formData: {
              token: '8337effca0ddfcd9c5899f3509b23657'
            },
            success: ({ data }) => {
              data = JSON.parse(data)
              if (data.code !== 200) {
                uni.showToast({
                  icon: 'error',
                  title: data.message
                })
                return
              } else {
                uploadedURL.value.push(data.url)
                // console.log(uploadedURL.value);
              }
            },
            fail: (err) => {
              console.log('图片上传失败：', err)
              reject()
            },
            complete: () => {
              if (uploadedURL.value.length === imageVal.value.length) {
                resolve()
              }
            }
          })
        })
      }).then(() => {
        console.log(categoryID.value, title.value, content.value, uploadedURL.value)
      })
    }
    // 调用接口
    await CreateCircle({
      categoryID: categoryID.value,
      title: title.value,
      content: content.value,
      images: JSON.stringify(uploadedURL.value)
    }).then((res) => {
      uni.showToast({
        icon: 'success',
        title: '发布成功'
      })
      uni.navigateBack()
    })
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 0 20rpx;

    .item {
      margin-bottom: 20rpx;

      .title {
        font-size: 24rpx;
        color: #000;
        margin-bottom: 10rpx;
      }
    }

    .info {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #666;
    }
  }
</style>
